package com.testapis.test.dao;

import com.testapis.test.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

@Component
public class PersonDao {
    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 创建对象
     */
    public boolean savePerson(Person person) {
        mongoTemplate.save(person);
        return true;
    }

    /**
     * 根据用户名查询对象
     * @return
     */
    public Person findTestByName(String name) {
        Query query=new Query(Criteria.where("name").is(name));
        Person person =  mongoTemplate.findOne(query , Person.class);
        return person;
    }

    /**
     * 更新对象
     */
    public void updateTest(Person person) {
        Query query=new Query(Criteria.where("id").is(person.getId()));
        Update update= new Update().set("age", person.getPro()).set("name", person.getName());
        //更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query,update,Person.class);
    }

    /**
     * 删除对象
     * @param id
     */
    public void deleteTestById(Integer id) {
        Query query=new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query,Person.class);
    }

}
